<?php
class daka_class_listAction extends backendAction{
    public function _initialize() {
        parent::_initialize();
        $this->_mod = D('daka_class_list');
    }
	public function _before_index() {
        
    }
    //列表页
    public function index() {
        $sort = $this->_request("sort", 'trim', 'ordid');
        $order = $this->_request("order", 'trim', 'ASC');
        $tree = new Tree();
        $tree->icon = array('│ ','├─ ','└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $pid=$this->_get('pid','intval',0);
        
        $map=array();
        if($pid)$map['pid']=$pid;
        
        $result = $this->_mod->where($map)->order($sort . ' ' . $order)->relation(true)->select();
        $tree->init($result);
        $list = $tree->get_tree_arr($pid);
        //dump($list);die;
        $this->assign('list', $list);
        $this->assign('pid',$pid);
        $this->display();
    }

   //批量选择列表页
    public function getindex() {
        $tree = new Tree();
        $tree->icon = array('│ ','├─ ','└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
       $map=array();
        $map['id']=array('in',implode(',',$this->_mod->get_child_ids(1)));
        $result = $this->_mod->where($map)->order('ordid asc,id asc')->select();
        $array = array();
        foreach($result as $r) {
        	$r['icos']='';
        	if($r['img']){

        	  $r['icos']='<img   src="'.attach($r['img'],'',$r['ategory']).'" width="32" height="32"/>';
        	}
            $r['str_status'] = '<img src="./media/image/toggle_' . ($r['status'] == 0 ? 'disabled' : 'enabled') . '.gif" />';
            $r['str_show'] = '<img src="./media/image/toggle_' . ($r['show'] == 0 ? 'disabled' : 'enabled') . '.gif" />';
            $r['parentid_node'] = ($r['pid'])? ' class="child-of-node-'.$r['pid'].'"' : '';
            $array[] = $r;
        }
        $str  = "<tr id='node-\$id' \$parentid_node>
                <td align='center'><input type='checkbox' value='\$id' data-name='\$name' class='J_checkitem'></td>
                <td>\$spacer<span>\$name</span></td>
                <td align='center'>\$icos</td><td align='center'>\$id</td>
                </tr>";
        $tree->init($array);
        $list = $tree->get_tree(1, $str);
		
        $this->assign('list', $list);
        $this->assign('list_table', true);
        //去掉刷新
        $_GET['isfull']=1;
        $this->display();
    }


    /**
     * 添加子菜单上级默认选中本栏目
     */
    public function _before_add() {
        $pid = $this->_get('pid', 'intval', 0);
        $map['type'] = 0;
        $order = 'ordid asc';
		$tree = new Tree();
		$result = $this->_mod->where($map)->order($order)->select();
		$array = array();
		foreach($result as $r) {
			$r['selected'] = $r['id'] == $_GET['pid'] ? 'selected' : '';
			$array[] = $r;
		}
		$str  = "<option data-spacer='\$spacer' value='\$id' \$selected>\$spacer \$title</option>";
		$tree->init($array);
		$select_menus = $tree->get_tree(0, $str);
		$this->assign('select_menus', $select_menus);
		
		$paper = M('daka_paper')->where(array('class_id'=>1,'status'=>1))->order('ordid asc,time desc')->select();
        $this->assign('paper', $paper);
		
		$daka_user = M('daka_user')->where('status=1')->select();
        $this->assign('daka_user', $daka_user);
    }

   public function _before_edit() {
	    $id = $this->_get('id','intval');
        $info = $this->_mod->find($id);
        $this->assign('info', $info);
        
        $map['type'] = 0;
        $order = 'ordid asc';
		$tree = new Tree();
		$result = $this->_mod->where($map)->order($order)->select();
		$array = array();
		foreach($result as $r) {
			$r['selected'] = $r['id'] == $info['pid'] ? 'selected' : '';
			$array[] = $r;
		}
		$str  = "<option data-spacer='\$spacer' value='\$id' \$selected>\$spacer \$title</option>";
		$tree->init($array);
		$select_menus = $tree->get_tree(0, $str);
		$this->assign('select_menus', $select_menus);
        
		$paper = M('daka_paper')->where(array('class_id'=>1,'status'=>1))->order('ordid asc,time desc')->select();
        $this->assign('paper', $paper);
		
		$daka_user = M('daka_user')->where('status=1')->select();
        $this->assign('daka_user', $daka_user);
    }

    /**
     * 入库数据整理
     */
    protected function _before_insert($data = '') {
		//判断类型是单元节点 还是 讲座详情
		if($data['type']==0){
			//单元节点  就删除 讲师信息 和 课堂内容
			unset($data['uid']);
			unset($data['content']);
			unset($data['paper_id']);
		}else{
			if($data['uid'] == ''){
				$this->error('讲师不能为空');
			}
			if($data['content'] == ''){
				$this->error('课堂描述不能为空');
			}
			if($data['paper_id'] == ''){
				$this->error('课堂文章不能为空');
			}
		}
		
        //生成spid
        $data['spid'] = $this->_mod->get_spid($data['pid']);
        return $data;
    }

    /**
     * 修改提交对数据
     */
    protected function _before_update($data = '') {
		//dump($data);die;
		//判断类型是单元节点 还是 讲座详情
		if($data['type']==0){
			//单元节点  就删除 讲师信息 和 课堂内容
			unset($data['uid']);
			unset($data['content']);
			unset($data['paper_id']);
		}else{
			if($data['uid'] == ''){
				$this->error('讲师不能为空');
			}
			if($data['content'] == ''){
				$this->error('课堂描述不能为空');
			}
			if($data['paper_id'] == ''){
				$this->error('课堂文章不能为空');
			}
		}
		$data['content'] = trim($data['content']);
        $old_pid = $this->_mod->field('pid')->where(array('id'=>$data['id']))->find();
        if ($data['pid'] != $old_pid['pid']) {
            //不能把自己放到自己或者自己的子目录们下面
            $wp_spid_arr = $this->_mod->get_child_ids($data['id'], true);
            if (in_array($data['pid'], $wp_spid_arr)) {
                $this->error('不能移动子类');
            }
            //重新生成spid
            $data['spid'] = $this->_mod->get_spid($data['pid']);
        }
        return $data;
    }
	
	public function ajax_get_cid() {
        $id = $this->_get('id', 'intval');
        $class_id = $this->_get('class_id', 'intval',0);
		if($class_id){
			$return = $this->_mod->field('id,title')->where(array('pid'=>$id,'class_id'=>$class_id))->select();
			//dump($this->_mod);die;
			if ($return) {
				$this->ajaxReturn(1, '操作成功', $return);
			} else {
				$this->ajaxReturn(0, '操作失败');
			}	
		}
        
    }
   /***
    *  @todo获取列表,按变量
    *  当操作需要获取分配权限时，请在菜单中加入辞操作方法。否责多权限分配失败
    * **/
    public function ajax_getchilds() {
        $var = $this->_get('id', 'trim');
        $level=$this->_get('level','intval',0);
        $pid= $this->_mod->where(array('variable'=>$var))->getField('id');
        $return = $this->_mod->field('id,name,variable')->where(array('pid'=>$pid))->order('ordid DESC')->select();
        if ($return) {
        	if($level==2){  //有二级,生成目录
                 foreach($return as $k=>$v){
                     $return[$k]['sub']= $this->_mod->field('id,name,variable')->where(array('pid'=>$v['id']))->order('ordid DESC')->select();
                 }
        	}
            $this->ajaxReturn(1,'操作成功', $return);
        } else {
            $this->ajaxReturn(0,'操作失败');
        }
    }
	 public function ajax_getchildss() {
        $id = $this->_get('id', 'intval');
        $return = $this->_mod->field('id,name')->where(array('pid'=>$id))->select();
        if ($return) {
            $this->ajaxReturn(1, '操作成功', $return);
        } else {
            $this->ajaxReturn(0, '操作失败');
        }
    }
    /**
     * @todo 删除之前判断是否有子类,有子类不可删除
     * */
   public function delete(){
       $ids = trim($this->_request('id'), ',');
       $rs=$this->_mod->where(array('pid'=>array('in',$ids)))->count('id');
       if($rs){
          IS_AJAX && $this->ajaxReturn(0,'该类不可删除,请先删除子分类');
          $this->error('该类不可删除,请先删除子分类');
       }else{
	        if ($ids) {
	            if (false !==$this->_mod->delete($ids)) {
	                IS_AJAX && $this->ajaxReturn(1,'操作成功');
	                $this->success('操作成功');
	            } else {
	                IS_AJAX && $this->ajaxReturn(0,'操作失败');
	                $this->error('操作失败');
	            }
	        } else {
	            IS_AJAX && $this->ajaxReturn(0, '操作失败');
	            $this->error('操作失败');
	        }
       }
    }
   public function creat_custom_menu()
    {

		$wxsign=new Wxjssdk();
		$access_token=$wxsign->getAccessToken();//获取到ACCESS_TOKEN
    	if($access_token!='')
    	{
    		$data=$this->getmenu();
    		$msg=$this->curl_menu($access_token,$data);
	        if($msg['errmsg']=='ok')
	        {
	        	$this->ajaxReturn(1,'创建自定义菜单成功!');
	        }
	        else {
	        	$this->ajaxReturn(0,'创建自定义菜单失败!');
	        }

    	}else
    	{
    		$this->ajaxReturn(0,'创建失败,'.$ACCESS_LIST['errmsg']);
    	}


    }
    //提交菜单
     public function curl_menu($ACCESS_TOKEN,$data)
     {
			$ch = curl_init();
			 curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$ACCESS_TOKEN);
			 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
			 curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
			 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			 curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
			 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			 $tmpInfo = curl_exec($ch);
			 if (curl_errno($ch)) {
				echo 'Errno'.curl_error($ch);
			 }
			 curl_close($ch);
			$arr= json_decode($tmpInfo,true);
			return $arr;
     }


    public function getmenu()
   {
   	    $keyword = array();
		$temp=get_article('menu','item_cate');
    	$topmemu= $this->_mod->field('id,name,variable')->where(array('pid'=>$temp['id'],'status'=>1))->order('ordid asc')->select();

    	foreach ($topmemu as $key )
    	{
    		$nextmenu= $this->_mod->field('id,name,variable')->where('pid='.$key['id'].' and status=1')->order('ordid asc')->select();
    		if(count($nextmenu)!=0)//没有下级栏目
    		{
                 foreach ($nextmenu as $key2)
                 {
                 	if(is_url($key2['variable'])){
    				     $kk[]=array('type'=>'view','name'=>$key2['name'],'url'=>$key2['variable']);
	    			}else{
	    				$kk[]=array('type'=>'click','name'=>$key2['name'],'key'=>$key2['variable']);
	    			}
                 }
                 $keyword['button'][]=array('name'=>$key['name'],'sub_button'=>$kk);
                 $kk='';
    		}else
    		{
    		   if(is_url($key['variable'])){
	            $keyword['button'][]=array('type'=>'view','name'=>$key['name'],'url'=>$key['variable']);
    		   }else{
    		   	$keyword['button'][]=array('type'=>'click','name'=>$key['name'],'key'=>$key['variable']);
    		   }


    		}
    	}
       return	json_encode($keyword, JSON_UNESCAPED_UNICODE);
   }
}